import React, { useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { PlusOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons';
import { Button, Switch, message, Popconfirm, Image } from 'antd';
import { getAdver, editAdverStatus, delAdver, addAdverData, editAdver } from '@/services/adver';
import HandleFunc from './components/HandleFunc';

const Index = () => {
  // 添加 模态框是否显示 状态
  const [isModalVisible, setIsModalVisible] = useState(false);
  // 添加 模态框是否显示 状态
  const [editId, setEditId] = useState(undefined);
  // 初始化数据列表 定义设置状态
  const ref = useRef();


  // 表格字段
  const columns = [
    {
      title: '广告名称',
      dataIndex: 'title',
      ellipsis: true,
    },
    {
      title: '广告地址',
      dataIndex: 'url',
    },
    {
      title: '广告图片',
      dataIndex: 'img_url',
      hideInSearch: true,
      render: (_, record) => <Image width={64} src={record.img_url} />,
    },
    {
      title: '广告状态',
      dataIndex: 'status',
      hideInSearch: true,
      render: (_, record) => {
        return (
          <Switch
            checkedChildren="开启"
            unCheckedChildren="关闭"
            onChange={async () => {
              const changeSwitch = await editAdverStatus(record.id);
              if (changeSwitch.status === undefined) {
                message.success('改变状态成功');
              }
            }}
            defaultChecked={record.status == 0 ? false : true}
          />
        );
      },
    },
    {
      title: '广告排序',
      dataIndex: 'seq',
      hideInSearch: true,
    },
    {
      title: '编辑',
      render: (_, record) => {
        return (
          <div>
            <Popconfirm
              title="你确定要删除吗？"
              onConfirm={async () => {
                const response = await delAdver(record.id);
                if (response.status === undefined) {
                  message.success('删除成功');
                  ref.current.reload();
                } else {
                  message.error('删除失败');
                }
              }}
              okText="确认"
            >
              <Button type="primary" danger shape="circle" icon={<DeleteOutlined />} />
            </Popconfirm>
            &nbsp;&nbsp;
            <Button
              type="primary"
              shape="circle"
              onClick={() => showModal(true, record.id)}
              icon={<EditOutlined />}
            />
            &nbsp;&nbsp;
          </div>
        );
      },
    },
  ];

  // 获取广告数据列表
  const getAdverData = async (params) => {
    const data = {
      title: params.title,
      status: params.status,
      url: params.url,
    };
    const res = await getAdver(data, params.current);
    return {
      data: res.data,
      success: true,
      total: res.meta.pagination.total,
    };
  };

  // 添加广告
  const AddOrEdit = async (data, uid = undefined) => {
    if (uid == undefined) {
      //添加
      console.log(data);
      data.status = data.status ? 1 : 0;
      const res = await addAdverData(data);
      if (res.status === undefined) {
        message.success('添加广告成功');
        setIsModalVisible(false);
        ref.current.reload();
      } else {
        message.error('添加失败');
      }
    } else {
      //修改
      const response = await editAdver(uid, data);
      if (response.status === undefined) {
        message.success('修改广告成功');
        setIsModalVisible(false);
        ref.current.reload();
      } else {
        message.success('修改广告失败');
      }
    }
  };

  const showModal = async (show, uid = undefined) => {
    setIsModalVisible(show);
    setEditId(uid);
  };

  return (
    <PageContainer>
      <ProTable
        actionRef={ref}
        columns={columns}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          collapseRender: false,
        }}
        request={async (params = {}) => getAdverData(params)}
        dateFormatter="string"
        headerTitle="高级表格"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              showModal(true);
            }}
          >
            新建
          </Button>,
        ]}
      />

      {isModalVisible ? (
        <HandleFunc
          visible={isModalVisible}
          editId={editId}
          showModal={showModal}
          AddOrEdit={AddOrEdit}
        />
      ) : null}
    </PageContainer>
  );
};

export default Index;
